# -*- coding: utf-8 -*-
import os
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
from google.appengine.ext.webapp.util import run_wsgi_app
from django.newforms.util import ErrorList, ValidationError
import viaggiatreno

class TrainForm(djangoforms.ModelForm):
	class Meta:
		model = viaggiatreno.Train
		exclude = ['name', 'existent', 'info', 'stop_names']
	def clean_number(self):
		trainnumber = self.clean_data['number']
		if trainnumber<0: raise ValidationError("There're not negative train numbers!")
		if not viaggiatreno.train_existence(trainnumber):
			raise ValidationError("Today there's no "+str(trainnumber)+" train")
		return trainnumber

def formPage(request, form):
	path = os.path.join(os.path.dirname(__file__), 'index.html')
	request.response.out.write(template.render(path, {'form':form}))

def timetable_fullPage(request, trainNumber):
	train = viaggiatreno.Train(number=trainNumber)
	train.get_info()
	train.put()
	path = os.path.join(os.path.dirname(__file__), 'timetable_full.html')
	request.response.out.write(template.render(path, {'train': train,}))

def timetable_compactPage(request, trainNumber):
	train = viaggiatreno.Train(number=trainNumber)
	train.get_info()
	train.put()
	path = os.path.join(os.path.dirname(__file__), 'timetable_compact.html')
	full_url = "/timetable?number=%s&version=full" % trainNumber
	request.response.out.write(template.render(path, {'train': train, 'full_url': full_url,}))

def timetable_minimalPage(request, trainNumber):
	train = viaggiatreno.TrenitaliaTrainInfo(number=trainNumber)
	path = os.path.join(os.path.dirname(__file__), 'timetable_minimal.html')
	compact_url = "/timetable?number=%s&version=compact" % trainNumber
	request.response.out.write(template.render(path, {'train': train, 'compact_url': compact_url}))

class Main(webapp.RequestHandler):
	def get(self):
		formPage(self, TrainForm())

class Timetable(webapp.RequestHandler):
	def get(self):
		data = TrainForm(data=self.request.GET)
		if data.is_valid():
			trainNumber = data.clean_data['number']
			version = self.request.get('version')
			if version=='minimal':
				timetable_minimalPage(self, trainNumber)
			elif version=='compact':
				timetable_compactPage(self, trainNumber)
			elif version=='full':
				timetable_fullPage(self, trainNumber)
		else:
			formPage(self, data)


application = webapp.WSGIApplication([
		('/timetable', Timetable),
		('/.*', Main),
	],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
